/*
 * Copyright (c) 2023, 2024,yzc.cn All rights reserved.
 *
 */
package com.by.controller;

import com.alibaba.nacos.common.utils.MD5Utils;
import com.by.bean.LoginBean;
import com.by.common.bean.Result;
import com.by.common.utils.MapUtils;
import com.by.common.utils.TokenUtils;
import com.by.pojo.SUser;
import com.by.server.UserServer;
import io.swagger.annotations.Api;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.Map;

/**
 * <p>Project: erp-cloud-api - UserController</p>
 * <p>Powered by yzc On 2024-01-23 11:33:59</p>
 * <p>描述：<p>
 *
 * @author yzc [youzhicheng0415@163.com]
 * @version 1.0
 * @since 17
 */
@RestController
@RequestMapping("/v1")
@Api(tags = {"用户管理"})
public class UserController {
    @Autowired
    UserServer userServer;

    @PostMapping("/user/login")
    public Result login(@RequestBody LoginBean loginBean){
        SUser user = userServer.queryUser(loginBean.getUsername());
        if (user == null){
            return Result.error("账号不存在");
        }
        String pwd = DigestUtils.md5DigestAsHex(loginBean.getPassword().getBytes());
        if (!user.getPassword().equals(pwd)){
            return Result.error("账号或密码错误");
        }
        if (user.getStatus() == 2){
            return Result.error("该账号已被禁用，请联系管理员");
        }
        //将javabean装换成map
        Map map = MapUtils.convert(user);
        //移除密码
        map.remove("password");
        //查询权限
        String permissions = userServer.queryPermissions(user.getRoleId());
        map.put("permissions",permissions);

        //生成token
        String  token = TokenUtils.getToken( map);
        map.put("token",token);


        return Result.success(map);
    }
}
